package vm.runtime;


import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;

public class TypeParse {

    public static Class<?> getArrayListGenericType(Object list) {
        if (!(list instanceof ArrayList)) {
            throw new IllegalArgumentException("Provided object is not an instance of ArrayList.");
        }

        ArrayList<?> arrayList = (ArrayList<?>) list;
        if (arrayList.isEmpty()) {
            return Object.class; // 如果ArrayList为空，则无法推断类型
        }

        // 获取ArrayList的Class对象
        Type type = arrayList.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType paramType = (ParameterizedType) type;
            Type[] typeArgs = paramType.getActualTypeArguments();
            if (typeArgs.length > 0 && typeArgs[0] instanceof Class) {
                return (Class<?>) typeArgs[0];
            }
        }

        // 如果无法通过ParameterizedType获取类型，则检查ArrayList中的元素类型
        Object firstElement = arrayList.get(0);
        return firstElement != null ? firstElement.getClass() : Object.class;
    }


    public static String getType(Object object) {
        if (object instanceof String) {
            return "string";
        }
        else if (object instanceof Integer) {
            return "int";
        }
        else if (object instanceof Boolean) {
            return "bool";
        }
        else if (object instanceof OutputStream) {
            return "output";
        }
        else if (object instanceof InputStream) {
            return "input";
        }
        else if (object instanceof byte[]) {
            return "byte[]";
        }
        else if (object instanceof Thread) {
            return "thread";
        }
        else if (object instanceof Long) {
            return "long";
        }
        else if (object instanceof NextVMRuntime) {
            NextVMRuntime nextVMRuntime = (NextVMRuntime) object;
            return nextVMRuntime.FunctionType;
        }
        else if (object instanceof ArrayList<?>) {
            Class<?> genericType = getArrayListGenericType((ArrayList<?>) object);
            String Type = genericType.getSimpleName().toLowerCase();
            if (Type.equals("string")) {
                return "string[]";
            }
            else if (Type.equals("integer") || Type.equals("int")) {
                return "int[]";
            }
            else if (Type.equals("double")) {
                return "double";
            }
            else if (Type.equals("float")) {
                return "float[]";
            }
            else if (Type.equals("long")) {
                return "long[]";
            }
            else {
                return null;
            }
        }
        else {
            return null;
        }
    }
}
